package cn.jsp.spring.dao;

import cn.jsp.spring.domain.Stu;
import cn.jsp.spring.jdbc.GeneralRowProcessor;
import cn.jsp.spring.jdbc.RowProcessor;
import lombok.SneakyThrows;
import org.hsqldb.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
@Repository
public class BaseDao<T> {
  @Autowired //自动绑定，默认按照类型绑定
  DataSource dataSource;
  @SneakyThrows
  public List<T> query(String sql, RowProcessor<T> rowProcessor, Object...params){
    List<T> stus=new ArrayList<>();
    try (Connection con = dataSource.getConnection();
         PreparedStatement pstmt = con.prepareStatement(sql);
         ResultSet rs = pstmt.executeQuery()) {
      while (rs.next()) {
        T stu=rowProcessor.process(rs);
        stus.add(stu);
      }
    }
    return stus;
  }
  @SneakyThrows
  public List<T> find(String sql,Class<T> target, Object...params){
    List<T> stus=new ArrayList<>();
    RowProcessor<T> rowProcessor=new GeneralRowProcessor<>(target);
    try (Connection con = dataSource.getConnection();
         PreparedStatement pstmt = con.prepareStatement(sql);
         ResultSet rs = pstmt.executeQuery()) {
      while (rs.next()) {
        T stu=rowProcessor.process(rs);
        stus.add(stu);
      }
    }
    return stus;
  }

}
